package com.inews.base.persistence;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;
import com.inews.base.utils.Identities;
import com.inews.base.utils.InewsUtils;

public class SearchFilter {

	public enum Operator {
		EQ, IN, ISNULL, LIKE, GT, LT, GTE, LTE, NE
	}

	public String fieldName;
	public Object value;
	public Operator operator;

	public SearchFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	public static Map<String, SearchFilter> parse(Map<String, Object> filterParams) {
		Map<String, SearchFilter> filters = Maps.newHashMap();

		for (Entry<String, Object> entry : filterParams.entrySet()) {
			String[] names = StringUtils.split(entry.getKey(), "_");
			Object value = entry.getValue();
			if (names.length < 2) {
				throw new IllegalArgumentException(entry.getKey() + " is not a valid search filter name");
			}
			if(names.length  == 3 && InewsUtils.isNotEmpty(value)){
				if("DATE".equals(names[2])){
					String fieldValue = (String)value;
					fieldValue = fieldValue.replace("T", "").replace(":", "").replace("-", "");
					value = fieldValue.substring(0, 8);
				}else if("TIME".equals(names[2])){
					String fieldValue = (String)value;
					fieldValue = fieldValue.replace("T", "").replace(":", "").replace("-", "");
					value = fieldValue;
				}
			}
			SearchFilter filter = new SearchFilter(names[1], Operator.valueOf(names[0]), value);
			if(InewsUtils.isNotEmpty(entry.getValue())){
				filters.put(filter.fieldName + Identities.uuid2(), filter);
			}
		}
		return filters;
	}
}
